home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10416 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  62 lines

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Converting Strings to Upper Case
  5. Date: 17 Mar 1996 18:20:06 GMT
  6. Organization: Nando.net Public Access
  7. Message-ID: <4ihl4m$4ca@castle.nando.net>
  8. References: <4ifra6$52i@scipio.cyberstore.ca> <4ih7l3$526@thrush.sover.net>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: grail2113.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4ih7l3$526@thrush.sover.net>, mountain@sover.net (Steve Mount) writes:
  14. >In article <4ifra6$52i@scipio.cyberstore.ca>, ejw@news.cyberstore.ca says...
  15. >>I need to write a function to convert a string containg upper or lower case
  16. >>characters to the opposite case.  Something like:
  17. >>
  18. >>  void libConvertUpperCase(char *str);  and
  19. >>  void libConvertLowerCase(char *str);
  20. >>
  21. >>and the string would be modified.  I just can't seem to wrap my head around 
  22. >>the best way that I know is better than writing a for loop to check each 
  23. >>element in the array?
  24. >
  25. >My home compiler has strlwr and strupr functions.  At work, we don't, so
  26. >just to make it work, quick and dirty, I did:
  27. >
  28. >void strnlwr(char *buffer, int len)
  29. >{
  30. >register int i;
  31. >for (i=0;i<len;i++) buffer[i] = tolower(buffer[i]);
  32. >return;
  33. >}
  34.  
  35. A couple of comments on this solution.  The inclusion of the parameter
  36. len is problematic.  First the user must obtain a length before the call.
  37. Second, not having a check in the function, conversion may continue
  38. beyond the end of the string.
  39.  
  40. Also the function returns nothing.  It is convenient to return a pointer.
  41.  
  42. Also, char may be signed and should therefore be cast before apply-
  43. ing tolower().  Finally, it is always a good idea to declare a function
  44. before using it.
  45.  
  46. #include <ctype.h>
  47.  
  48. char *mystr2lwr( char *s )
  49. {
  50.    char *t = s;
  51.  
  52.    if ( t != NULL )
  53.       while ( *s )
  54.          *s++ = tolower( (unsigned char)*s );
  55.  
  56.    return t;
  57. }
  58.  
  59. Bill McCarthy
  60. actuary@nando.net
  61. Wendell, NC  USA
  62.